import numpy as np
from sklearn.cluster import KMeans
from tornado.web import RequestHandler
import json
import common as com
from logHandler import getLogger
from timeoutHandler import set_timeout


class KmeansVo(object):
    def __init__(self, trainDataList):
        self.trainDataList = trainDataList

def dictToKmeansVo(d):
    return KmeansVo(d["trainDataList"])

class IndexKMeansHandler(RequestHandler):
    @set_timeout(com.timeoutTime)
    def post(self):
        try:
            jsonByte = self.request.body
            jsonStr = jsonByte.decode("utf-8")
            kmeansVo = json.loads(jsonStr, object_hook=dictToKmeansVo)
            log = getLogger()
            log.info("开始执行kmeans算法：{}".format(kmeansVo.__dict__))
            commonResponse = com.CommonResponse(com.errorCode, "无同聚类数据", dict([("list", [])]))
            data_array = kmeansVo.trainDataList
            yearSiteDataList = []
            for data_line in data_array:
                data_info = data_line.split("_")
                station_id = data_info[0]
                x_test = np.asarray(data_info[1], dtype=np.float32).reshape([-1, 1])
                yearList = []
                valueList = []
                yearValueList = data_info[2].split(",")
                for yearValue in yearValueList:
                    yearValueArray = yearValue.split(":")
                    yearList.append(yearValueArray[0])
                    valueList.append(yearValueArray[1])
                x_train = np.asarray(valueList, dtype=np.float32).reshape([-1, 1])
                kmeans = KMeans(n_clusters=5)
                kmeans.fit(x_train)
                y_predict = kmeans.predict(x_test)
                sameMeanYearList = []
                for index, y_mean in enumerate(kmeans.labels_):
                    if y_predict[0] == y_mean:
                        sameMeanYearList.append(yearList[index])
                yearSiteData = com.KmeansDto(station_id, sameMeanYearList)
                yearSiteDataList.append(yearSiteData.__dict__)
            commonResponse = com.CommonResponse(com.successCode, com.successMsg, dict([("list", yearSiteDataList)]))
            log.info("KMeans算法执行完毕")
        except BaseException as e:
            print("执行kmeans失败：{}".format(e))
            commonResponse = com.CommonResponse(com.errorCode, "{}".format(e), dict([("list", [])]))
            log.error("kmeans算法执行异常")
        finally:
            # 返回数据
            self.write(commonResponse.__dict__)

